package org.example.all;


import ch.ethz.ssh2.Connection;
import ch.ethz.ssh2.Session;
import ch.ethz.ssh2.StreamGobbler;
import com.sun.management.OperatingSystemMXBean;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.lang.management.ManagementFactory;
import java.util.Arrays;
import java.util.stream.Collectors;

import static com.sun.xml.internal.ws.policy.sourcemodel.wspolicy.XmlToken.Digest;

public class Cpu {
    private static OperatingSystemMXBean osmxb = (OperatingSystemMXBean) ManagementFactory.getOperatingSystemMXBean();
    public static void main(String[] args) throws IOException, InterruptedException {
        Connection connection = new Connection("10.10.11.4");
        connection.connect();
        boolean su = connection.authenticateWithPassword("myuser","123");
        System.out.println(su);
        // 创建会话
        Session sess = connection.openSession();
        // 执行命令
        sess.execCommand("echo '123' | sudo -S dmidecode -t 4 | grep ID;echo ':';"
                        +"echo '123' | sudo -S hdparm -I /dev/sda | grep 'Serial Number';echo ':';"
                        + "echo '123' | sudo -S lshw -c network | grep serial | head -n 1;"
                );
        // 获取返回值
        InputStream isIn = new StreamGobbler(sess.getStdout());
        while (isIn.available() == 0){
            Thread.sleep(100);
        }
        String sIn = getInputStream(isIn);
        String machineCode = Arrays.stream(sIn.split("[:\\s]"))
                .filter(x-> !(x.equals("") || x.equals("ID") || x.equalsIgnoreCase("Serial") || x.equals("Number")))
                .map(String::trim)
                .collect(Collectors.joining());
        System.out.println(machineCode);
        // 关闭会话
        sess.close();
        // 输出返回值
        System.out.println(sIn.trim());
    }


    // 获取流中内容
    public static String getInputStream(InputStream is) {
        BufferedReader br = new BufferedReader(new InputStreamReader(is));
        StringBuilder sb = new StringBuilder();
        try {
            if (is.available() != 0) {
                while (true) {
                    String line = br.readLine();
                    if (line != null) {
                        sb.append(line);
                    } else {
                        break;
                    }
                }
            }
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return sb.toString();
    }
}
